import React from 'react';
import { Tree } from 'antd';

const { TreeNode } = Tree;

class DragTree extends React.Component {

    state = {
        isFirst: false,
        data: [{ title: '河南', key: 'A100', children: [{ title: '郑州', key: 'A1001' }] }, { title: '上海', key: 'B1001', isLeaf: true }]
    }

    onDragEnter = info => {
        // console.log(info);
        // expandedKeys 需要受控时设置
        // this.setState({
        //   expandedKeys: info.expandedKeys,
        // });
    };

    onDrop = info => {
        console.log('innfo',info);
        const dropKey = info.node.props.eventKey;  // 代表拖动停到的树节点
        const dragKey = info.dragNode.props.eventKey;
        const dropPos = info.node.props.pos.split('-');
        const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);  // 代表停到树节点的上方或者下方，下方：1,上方：-1

        // console.log('info.dropPosition',info.dropPosition);
        // console.log('dropPos.length',dropPos.length);
        // console.log('-----','-------');

        // console.log('dropKey',dropKey);
        // console.log('dragKey',dragKey);
        // console.log('dropPos',dropPos);
        // console.log('dropPosition',dropPosition);

        const loop = (data, key, callback) => {
            data.forEach((item, index, arr) => {
                if (item.key === key) {
                    return callback(item, index, arr); // 递归函数出口
                }
                if (item.children) {
                    return loop(item.children, key, callback);
                }
            });
        };
        const data = [...this.state.data];  // 全部树数据

        // console.log('data',data);

        // Find dragObject
        let dragObj;
        loop(data, dragKey, (item, index, arr) => {
            arr.splice(index, 1); // 在拖动的树节点的同级节点，删除当前拖动dragKey值的树节点
            dragObj = item;  // 将删除的树节点保存
        });

        // console.log('info.dropToGap',info.dropToGap);

        if (!info.dropToGap) {  // dropToGap是否停到两个树节点之间（true），如果停留树节点其中，则为false
            // Drop on the content
            loop(data, dropKey, item => {
                item.children = item.children || [];
                // where to insert 示例添加到尾部，可以是随意位置
                item.children.push(dragObj);
            });
        } else if (
            // 这段判断是：当被拖动的树节点停在有子节点的树节点的下方位置时，会被认为被拖动的(dragKey)树节点将移动到停留（dropKey）树节点的首部位置
            (info.node.props.children || []).length > 0 && // Has children
            info.node.props.expanded && // Is expanded
            dropPosition === 1 // On the bottom gap
        ) {
            loop(data, dropKey, item => {
                item.children = item.children || [];
                // where to insert 示例添加到首部，可以是随意位置
                item.children.unshift(dragObj);
            });
        } else {
            let ar;
            let i;
            loop(data, dropKey, (item, index, arr) => {
                ar = arr;
                i = index;
            });
            if (dropPosition === -1) {
                ar.splice(i, 0, dragObj);
            } else {
                ar.splice(i + 1, 0, dragObj);
            }
        }

        this.setState({
            data,
        });
    };

    render() {
        const { data } = this.state;
        const generateTree = data =>
            data.map(item => {
                if (item.children && item.children.length) {
                    return (
                        <TreeNode key={item.key} title={item.title}>
                            {generateTree(item.children)}
                        </TreeNode>
                    );
                }
                return <TreeNode key={item.key} title={item.title} />;
            });

        return (
            <Tree
                draggable
                blockNode
                onDragEnter={this.onDragEnter}
                onDrop={this.onDrop}
            >
                {generateTree(data)}
            </Tree>
        )
    }
}

export default DragTree;